/**
 * Main process internationalization (i18n) utility
 * Supports multiple languages with fallback to English
 */

import fs from 'fs'
import path from 'path'
import { app } from 'electron'

let translations = null
let currentLanguage = 'zh-CN'

/**
 * Load translations from JSON files
 */
function loadTranslations () {
  if (translations) {
    return translations
  }

  // Try multiple possible paths for locale files
  let localesPath = null
  
  // Get app path safely (may not be available during early initialization)
  let appPath = null
  try {
    appPath = app.getAppPath()
  } catch (err) {
    console.warn('app.getAppPath() not available yet:', err.message)
  }

  const possiblePaths = [
    // Development mode: from source directory (relative to current file)
    path.join(__dirname, '../renderer/i18n/locales'),
    // Development mode: from app path (if available)
    appPath ? path.join(appPath, 'src/renderer/i18n/locales') : null,
    // Production mode: from app path (dist)
    appPath ? path.join(appPath, 'dist/electron/renderer/i18n/locales') : null,
    // Alternative: from dist directory (relative)
    path.join(__dirname, '../../renderer/i18n/locales'),
    // Fallback: try relative to current file (going up more levels)
    path.resolve(__dirname, '../../../src/renderer/i18n/locales'),
    // Another fallback: from app root (if available)
    appPath ? path.resolve(appPath, 'src/renderer/i18n/locales') : null
  ].filter(p => p !== null)

  console.log('Looking for locale files. App path:', appPath || 'not available')
  console.log('__dirname:', __dirname)
  
  // Find the first path that exists
  for (const testPath of possiblePaths) {
    const testFile = path.join(testPath, 'en.json')
    if (fs.existsSync(testFile)) {
      localesPath = testPath
      console.log('Found locale files at:', localesPath)
      break
    } else {
      console.log('Tried path (not found):', testPath)
    }
  }

  if (!localesPath) {
    console.error('Failed to find locale files. Tried paths:', possiblePaths)
    translations = {
      en: {},
      'zh-CN': {},
      'zh-TW': {}
    }
    return translations
  }

  try {
    translations = {
      en: JSON.parse(fs.readFileSync(path.join(localesPath, 'en.json'), 'utf8')),
      'zh-CN': JSON.parse(fs.readFileSync(path.join(localesPath, 'zh-CN.json'), 'utf8')),
      'zh-TW': JSON.parse(fs.readFileSync(path.join(localesPath, 'zh-TW.json'), 'utf8'))
    }
    console.log('Loaded translations from:', localesPath)
  } catch (err) {
    console.error('Failed to load translations from', localesPath, ':', err)
    translations = {
      en: {},
      'zh-CN': {},
      'zh-TW': {}
    }
  }
  return translations
}

/**
 * Set the current language
 * @param {string} lang - Language code (e.g., 'en', 'zh-CN', 'zh-TW')
 */
export function setLanguage (lang) {
  loadTranslations()
  if (translations[lang]) {
    currentLanguage = lang
  } else {
    // Fallback to English if language not found
    currentLanguage = 'en'
  }
}

/**
 * Get the current language
 * @returns {string} Current language code
 */
export function getLanguage () {
  return currentLanguage
}

/**
 * Translate a key to the current language
 * @param {string} key - Translation key (supports dot notation, e.g., 'menu.file.new')
 * @param {object} params - Optional parameters for interpolation
 * @returns {string} Translated string or the key if translation not found
 */
export function t (key, params = {}) {
  loadTranslations()
  
  // Check if translations are loaded
  if (!translations || Object.keys(translations.en).length === 0) {
    console.warn('Translations not loaded, returning key:', key)
    return key
  }

  const keys = key.split('.')
  let translation = translations[currentLanguage] || translations.en

  // Navigate through nested object
  for (const k of keys) {
    if (translation && typeof translation === 'object' && translation[k] !== undefined) {
      translation = translation[k]
    } else {
      // Fallback to English
      translation = translations.en
      for (const k2 of keys) {
        if (translation && typeof translation === 'object' && translation[k2] !== undefined) {
          translation = translation[k2]
        } else {
          console.warn('Translation not found for key:', key, 'at:', k2)
          return key // Return key if translation not found
        }
      }
      break
    }
  }

  // If translation is a string, interpolate parameters
  if (typeof translation === 'string') {
    return translation.replace(/\{\{(\w+)\}\}/g, (match, paramKey) => {
      return params[paramKey] !== undefined ? params[paramKey] : match
    })
  }

  // If translation is not a string, return the key
  if (typeof translation !== 'string') {
    console.warn('Translation for key', key, 'is not a string:', typeof translation, translation)
    return key
  }

  return translation
}

/**
 * Initialize i18n with a language
 * @param {string} lang - Language code
 */
export function initI18n (lang) {
  setLanguage(lang)
}

export default {
  setLanguage,
  getLanguage,
  t,
  initI18n
}

